package utils

import (
	"cloud-storage/lib"
	"errors"
	"go.uber.org/zap"
	"mime/multipart"
	"os"
	"path"
	"strings"
)

// GetFileTypeInt 判断文件后缀获取类型id
func GetFileTypeInt(filePrefix string) int {
	filePrefix = strings.ToLower(filePrefix)
	if filePrefix == ".doc" || filePrefix == ".docx" || filePrefix == ".txt" || filePrefix == ".pdf" {
		return 1
	}
	if filePrefix == ".jpg" || filePrefix == ".png" || filePrefix == ".gif" || filePrefix == ".jpeg" {
		return 2
	}
	if filePrefix == ".mp4" || filePrefix == ".avi" || filePrefix == ".mov" || filePrefix == ".rmvb" || filePrefix == ".rm" {
		return 3
	}
	if filePrefix == ".mp3" || filePrefix == ".cda" || filePrefix == ".wav" || filePrefix == ".wma" || filePrefix == ".ogg" {
		return 4
	}

	return 5
}

//GetName 对文件名进行加密
func GetName(name string) string {
	//获取文件扩展名
	ext := path.Ext(name)
	//根据扩展名进行分割
	fileName := strings.TrimSuffix(name, ext)
	fileName = EnCodeMD5(fileName)
	return fileName + ext
}

// CheckSize 判断文件大小是否超标
func CheckSize(f *multipart.FileHeader, size int64) bool {
	return f.Size <= size
}

// CheckDir 检查图片
func CheckDir(src string) error {
	// Getwd 返回对应的根路径名
	dir, err := os.Getwd()
	if err != nil {
		zap.L().Error("function os.Getwd() Filed", zap.Any("err", err.Error()))
		return errors.New("function os.Getwd() failed,err" + err.Error())
	}
	//判断是否存在该文件
	err = IsNotExistMkDir(dir + "/" + src)
	if err != nil {
		zap.L().Error("function IsNotExistMkDir() Filed", zap.Any("err", err.Error()))
		return errors.New("function IsNotExistMkDir() failed,err" + err.Error())
	}
	return nil
}

//IsNotExistMkDir 判断文件是否存在，如果不存在则新建文件夹
func IsNotExistMkDir(src string) error {
	_, err := os.Stat(src)
	if os.IsNotExist(err) == true {
		//创建文件
		err = os.MkdirAll(src, os.ModePerm)
		if err != nil {
			return err
		}
	}
	return nil
}

// GetFullPath 获取文件全路径
func GetFullPath(filePath string) string {
	return lib.AppSetting.RuntimeRootPath + filePath
}
